package com.sgb.kjwl.view.ui.fragment.home;

import android.Manifest;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.motion.widget.MotionLayout;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.google.android.material.tabs.TabLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentFindCarMapListBinding;
import com.sgb.kjwl.model.entity.transport.CarriageInfo;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.sgb.kjwl.model.entity.transport.GoodsSourceLocationEntity;
import com.sgb.kjwl.model.entity.transport.MapCarEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.utils.AddressHelper;
import com.sgb.kjwl.utils.ChineseEnglishAndNumberFilter;
import com.sgb.kjwl.utils.DefaultUtil;
import com.sgb.kjwl.utils.LocationUtil;
import com.sgb.kjwl.utils.NumberUtil;
import com.sgb.kjwl.utils.TextViewUtils;
import com.sgb.kjwl.utils.TouchHelper;
import com.sgb.kjwl.utils.VehicleConstant;
import com.sgb.kjwl.view.constant.RouterKey;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.swgk.core.event.MenuEvent;
import com.sgb.kjwl.view.ui.activity.MainActivity;
import com.sgb.kjwl.view.ui.activity.transport.CarriageDetailActivity;
import com.sgb.kjwl.view.ui.adapter.transport.CarriageListMultiTypeAdapter;
import com.sgb.kjwl.view.widget.GoodsTypePopWindow3;
import com.sgb.kjwl.view.widget.MapCarPopWindow;
import com.sgb.kjwl.view.widget.ThreeLevelAreaWindow;
import com.sgb.kjwl.viewmodel.carrierDemand.FindCarMapAndListModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.recyclerview.decoration.RecyclerViewItemDecoration;
import com.swgk.core.recyclerview.entity.BaseAreaEntity;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.PermissionUtils;
import com.swgk.core.util.ScreenUtil;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 承运需求 列表
 * 1.7.3更名为竞价找车、
 * 现在为物流首页使用，和图查货运大厅分开
 */

public class FindCarMapAndListFragment extends AppLazyFragment implements AMap.OnMarkerClickListener,
        AMap.OnCameraChangeListener {
    private int LOCATION_TYPE = 0;//0发货地，1目的地
    FindCarMapAndListModel viewModel;

    // 一级联动数据
    public List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;
    // 二级联动数据
    public List<List<AddressEntity<List<AddressEntity>>>> opt2 = new ArrayList<>();
    // 三级联动数据
    public List<List<List<AddressEntity>>> opt3 = new ArrayList<>();

    private ThreeLevelAreaWindow destinationPopWindow;

    FragmentFindCarMapListBinding binding;

    private List<GoodsInfoTypeEntity3> carsTypeData;
    private List<GoodsInfoTypeEntity3> carsLengthData;
    CarriageListMultiTypeAdapter carrierDemandListAdapter;
    //  private CarrierDemandListAdapter carrierDemandListAdapter; //接口完成 替换数据
    private int page = 1;
    private boolean isLoadMore = false;

    private int typePosition = -1;
    private int lengthPosition = 0;
    private int goodTypePosition = 0;
    private GoodsTypePopWindow3 carsTypePopWindow;
    private GoodsTypePopWindow3 carsLengthPopWindow;
    private GoodsTypePopWindow3 goodsTypePopWindow3;

    boolean isRefresh = true;
    boolean canShowListView = true;
    private ThreeLevelAreaWindow areaWindow;

    //地图控制器
    private AMap aMap;
    //当前定位位置信息
    public LatLng mCurLatLng;
    //地图缩放比例
    private float mZoom = 11;
    //最小缩放级别（全国）
    private final float mMinZoom = 3;
    //全国中心点经纬度
    private final LatLng mCenterLatLng = new LatLng(35.03349, 103.03319);
    private MapCarPopWindow mMapCarPop;//地图车辆弹窗
    public boolean mapShowing; //是否正在地图模式切换
    private boolean mIsNeedLoadByCamera;
    //屏幕高度
    private int mScreenWidth;
    //marker集合
    private final List<Marker> mMarkers = new ArrayList<>();
    //当前最后一个点击的marker
    private Marker mLastMarker;
    //初始车辆no
    private String mInitCarTypeNo;
    //是否是初始化,用于第一次定位后刷新列表数据
    private boolean mIsInit = true;
    //是否是展开的筛选栏，默认展开
    private boolean mIsExpand = true;
    //手势监听帮助类
    private TouchHelper mTouchHelper;
    boolean isCameraToPosition;

    //地图上的承运车辆数据集合(新请求下来的数据需要对比去重)
    private Map<String, MapCarEntity> carEntities = new HashMap<>();

    public static FindCarMapAndListFragment newInstance(String carNo, boolean canShowListView) {
        FindCarMapAndListFragment fragment = new FindCarMapAndListFragment();
        Bundle args = new Bundle();
        args.putString(RouterKey.NO, carNo);
        args.putBoolean("canShowListView", canShowListView);
        fragment.setArguments(args);
        return fragment;
    }

    public static FindCarMapAndListFragment newInstance(boolean param1, boolean canShowListView) {
        FindCarMapAndListFragment fragment = new FindCarMapAndListFragment();
        Bundle args = new Bundle();
        args.putBoolean("isRefresh", param1);
        args.putBoolean("canShowListView", canShowListView);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
//        DaggerCarrierDemandComponent.builder().appComponent(appComponent).carrierDemandModule(new CarrierDemandModule(this)).build().inject(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_find_car_map_list, container, false);
        viewModel = new ViewModelProvider(this).get(FindCarMapAndListModel.class);
        binding.setViewModel(viewModel);
        binding.mapFindCarByMap.onCreate(savedInstanceState);
        return binding.getRoot();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        if (getArguments() != null) {
            isRefresh = getArguments().getBoolean("isRefresh", true);
            canShowListView = getArguments().getBoolean("canShowListView", true);
            mInitCarTypeNo = getArguments().getString(RouterKey.NO);
            mapShowing = !canShowListView;
        }
    }

    public void initViews() {
        binding.mapAndListSwitch.setVisibility(canShowListView ? View.VISIBLE : View.GONE);
        binding.listDataLayout.setVisibility(canShowListView ? View.VISIBLE : View.GONE);
        binding.flMap.setVisibility(canShowListView ? View.GONE : View.VISIBLE);
        binding.etView.setFilters(new InputFilter[]{new ChineseEnglishAndNumberFilter()});
//        binding.tvFindCarByMapLoad.setVisibility(canShowListView ? View.GONE : View.VISIBLE);
//        binding.flExpand.setVisibility(mapShowing ? View.VISIBLE : View.GONE);
        binding.setOnClick(this);
        viewModel.setFragment(this);
        binding.messageNumLayout.setOnClickListener(this);
        binding.typeMore.setOnClickListener(this);
        binding.lengthMore.setOnClickListener(this);

        binding.carsList.setLayoutManager(new GridLayoutManager(getActivity(), 1));
        binding.carsList.addItemDecoration(new RecyclerViewItemDecoration(getResources().getDimension(R.dimen.dp5)));
        binding.carsList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull @NotNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (mIsExpand && dy > 30) {
                    binding.mlFilterRoot.transitionToEnd();
                }
            }
        });

        if (carrierDemandListAdapter == null) {
            carrierDemandListAdapter = new CarriageListMultiTypeAdapter(new ArrayList<>());
        }
        binding.carsList.setAdapter(carrierDemandListAdapter);
        carrierDemandListAdapter.setOnItemClickListener((adapter, view, position) ->
                CarriageDetailActivity.start(getActivity(), carrierDemandListAdapter.getData().get(position).getCarrierNo(), 1));

        if (!isRefresh) {
            binding.carsListRefreshLayout.setEnableRefresh(false);
            binding.llChangeMap.setVisibility(View.GONE);
        }

        binding.carsListRefreshLayout.setEnableLoadMore(true);
        binding.carsListRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                isLoadMore = true;
                page++;
                refreshDataByPage(page);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                isLoadMore = false;
                refreshData();
            }
        });
        //类型
        carsTypePopWindow = new GoodsTypePopWindow3(getActivity());
        carsTypePopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object type, Object key2, Object key3) {
                GoodsInfoTypeEntity3 entity = (GoodsInfoTypeEntity3) type;
                typePosition = (int) key2;

                binding.tabLayoutType.selectTab(binding.tabLayoutType.getTabAt(typePosition));
                viewModel.carType.set(entity);
                filterByCarType();
            }
        });
        carsTypePopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                binding.typeMore.setImageResource(R.mipmap.icon_tab_unfold);
            }
        });

        //车长
        binding.tabLayoutLength.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (null != carsLengthData && carsLengthData.size() > 0) {
                    lengthPosition = tab.getPosition();
                    viewModel.carLength.set(carsLengthData.get(lengthPosition));
                    refreshData();
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });

        //车长
        carsLengthPopWindow = new GoodsTypePopWindow3(getActivity());
        carsLengthPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object type, Object key2, Object key3) {
                GoodsInfoTypeEntity3 entity = (GoodsInfoTypeEntity3) type;
                lengthPosition = (int) key2;
                binding.carLen.setText(entity.getName());
                viewModel.carLength.set(entity);
                refreshData();
            }
        });
        carsLengthPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                String longs = binding.carLen.getText().toString();
                if (!longs.equals("车长")) {
                    binding.llCarlen.setBackgroundResource(R.drawable.shape_theme_coner);
                    TextViewUtils.changeTextView(getActivity(), binding.carLen, R.mipmap.ic_down_arrow, true);
                } else {
                    binding.llCarlen.setBackgroundResource(R.drawable.shape_gray_coner);
                    TextViewUtils.changeTextView(getActivity(), binding.carLen, R.mipmap.ic_down_arrow_n, false);
                }

            }
        });

        //找货类型
        goodsTypePopWindow3 = new GoodsTypePopWindow3(getActivity());
        goodsTypePopWindow3.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object type, Object key2, Object key3) {
                GoodsInfoTypeEntity3 entity = (GoodsInfoTypeEntity3) type;
                goodTypePosition = (int) key2;
                binding.goodsType.setText(entity.getName());
                viewModel.findGoodsType.set(entity);
                refreshData();
            }
        });
        goodsTypePopWindow3.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                String type = binding.goodsType.getText().toString();
                if (!type.equals("找货类型")) {
                    binding.llGoodsType.setBackgroundResource(R.drawable.shape_theme_coner);
                    TextViewUtils.changeTextView(getActivity(), binding.goodsType, R.mipmap.ic_down_arrow, true);
                } else {
                    binding.llGoodsType.setBackgroundResource(R.drawable.shape_gray_coner);
                    TextViewUtils.changeTextView(getActivity(), binding.goodsType, R.mipmap.ic_down_arrow_n, false);
                }
            }
        });

        //收货省份popWindow
        destinationPopWindow = new ThreeLevelAreaWindow(getActivity()) {
            @Override
            protected void resultContent(String name, String simpleName) {
                binding.tvDestination.setText(simpleName);
            }
        };
        destinationPopWindow.setShowOnlyAreaNoData(true);
        destinationPopWindow.setBgView(binding.grayLayout);
        destinationPopWindow.setAreaSingle();
        destinationPopWindow.setCitySingle();
        destinationPopWindow.setProvinceSingle();
        destinationPopWindow.setShowSimpleName(true);
        destinationPopWindow.setAllSingleSelect(true);
        destinationPopWindow.setOnlyShowProAndCity(true);
        destinationPopWindow.setOnResultClick(new ThreeLevelAreaWindow.OnResultClickProxy() {
            @Override
            protected void result(GoodsSourceLocationEntity entity) {
                viewModel.purposeLocation.set(entity);
                refreshData();
            }
        });
        destinationPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                String city = binding.tvDestination.getText().toString();
                if (!city.equals("目的地")) {
                    binding.llDestination.setBackgroundResource(R.drawable.shape_theme_coner);
                    TextViewUtils.changeTextView(getActivity(), binding.tvDestination, R.mipmap.ic_down_arrow, true);
                } else {
                    binding.llDestination.setBackgroundResource(R.drawable.shape_gray_coner);
                    TextViewUtils.changeTextView(getActivity(), binding.tvDestination, R.mipmap.ic_down_arrow_n, false);
                }

            }
        });

        areaWindow = new ThreeLevelAreaWindow(getActivity()) {
            @Override
            protected void resultContent(String name, String simpleName) {
                binding.tvSend.setText(simpleName);
                refreshData();
            }
        };
        areaWindow.setShowOnlyAreaNoData(true);
        areaWindow.setOnResultClick(new ThreeLevelAreaWindow.OnResultClickProxy() {
            @Override
            protected void result(GoodsSourceLocationEntity entity) {
                viewModel.sendLocation.set(entity);
                page = 1;
                isLoadMore = false;
                if ("不限".equals(entity.getProvinceName())) {
                    if (mapShowing) {
                        //地图缩小展示全中国
                        mZoom = mMinZoom;
                        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mCenterLatLng, mZoom));
                    } else {
                        refreshData();
                    }
                } else {
                    //查找经纬度刷新地图
                    viewModel.getLocation(getActivity(), viewModel.sendLocation.get().getCityName(), DefaultUtil.getString(viewModel.sendLocation.get().getAreaName()));
                }
            }
        });
        areaWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                String sendCity = binding.tvSend.getText().toString();
                if (!sendCity.equals("发货地")) {
                    binding.llSend.setBackgroundResource(R.drawable.shape_theme_coner);
                    TextViewUtils.changeTextView(getActivity(), binding.tvSend, R.mipmap.ic_down_arrow, true);
                } else {
                    binding.llSend.setBackgroundResource(R.drawable.shape_gray_coner);
                    TextViewUtils.changeTextView(getActivity(), binding.tvSend, R.mipmap.ic_down_arrow_n, false);
                }
            }
        });
        areaWindow.setAreaSingle();
        areaWindow.setCitySingle();
        areaWindow.setProvinceSingle();
        areaWindow.setShowSimpleName(true);
        areaWindow.setAllSingleSelect(true);
        areaWindow.setOnlyShowProAndCity(true);
        areaWindow.setBgView(binding.grayLayout);
        //根据省市区查找经纬度监听
        viewModel.ldLatLng.observe(this, latLng -> {
            if (latLng != null) {
                mZoom = 11;
                cameraToPosition(latLng.latitude, latLng.longitude);
                if (mIsInit) {
                    mIsInit = false;
                    refreshData();
                }
            }
        });

        //地图车辆弹窗
        mMapCarPop = new MapCarPopWindow(getContext());
        mMapCarPop.setOnDismissListener(this::resetOtherMarker);
        mMapCarPop.setOnClickCallBack(account -> {
            buildSingleTalking(account);
        });
        //地图找车数据
        viewModel.ldCars.observe(this, this::refreshMapMarker);
        //todo 筛选栏动画监听
        binding.mlFilterRoot.setTransitionListener(new MotionLayout.TransitionListener() {
            @Override
            public void onTransitionStarted(MotionLayout motionLayout, int i, int i1) {

            }

            @Override
            public void onTransitionChange(MotionLayout motionLayout, int i, int i1, float v) {

            }

            @Override
            public void onTransitionCompleted(MotionLayout motionLayout, int i) {
                mIsExpand = binding.mlFilterRoot.getProgress() == 0.0f;
                if (mIsExpand) {
                    binding.tvExpand.setText("收起筛选条件");
                    TextViewUtils.changeTextView(getActivity(), binding.tvExpand, R.drawable.btn_shop_up, false);
                } else {
                    binding.tvExpand.setText("更多筛选条件");
                    TextViewUtils.changeTextView(getActivity(), binding.tvExpand, R.drawable.btn_shop_down, false);
                }
            }

            @Override
            public void onTransitionTrigger(MotionLayout motionLayout, int i, boolean b, float v) {
            }
        });
    }

    private void initTabListener() {
        //类型
        binding.tabLayoutType.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (null != carsTypeData && carsTypeData.size() > 0) {
                    typePosition = tab.getPosition();
                    viewModel.carType.set(carsTypeData.get(tab.getPosition()));
                    filterByCarType();
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }

    /**
     * 还原其他marker
     */
    private void resetOtherMarker() {
        if (mLastMarker != null) {
            MapCarEntity entity = (MapCarEntity) mLastMarker.getObject();
            if (entity == null) {
                mLastMarker = null;
                return;
            }
            mLastMarker.setIcon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_find_car_marker_yellow));
            mLastMarker = null;
        }
    }

    /**
     * 根据经纬度移动地图，标记中心点
     */
    private void cameraToPosition(Double lat, Double lng) {
        if (lat == 0 || lng == 0) return;
        //标记不是用户滑动
        mIsNeedLoadByCamera = true;
        //切换地图中心点
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), mZoom));
        viewModel.ldLaction.getValue().setLatitude(lat);
        viewModel.ldLaction.getValue().setLongitude(lng);
    }

    @Override
    protected void onLazyLoad() {
        initViews();
        initMap();
        loadData();
    }

    /**
     * 初始化地图
     */
    private void initMap() {
        //获取地图控制类
        aMap = binding.mapFindCarByMap.getMap();
        //显示定位蓝点
        aMap.getUiSettings().setMyLocationButtonEnabled(false);
        //显示缩放控制器
        aMap.getUiSettings().setZoomControlsEnabled(false);
        //marker点击监听
        aMap.setOnMarkerClickListener(this);
        //监听地图移动
        aMap.setOnCameraChangeListener(this);
        //todo 手势监听
        aMap.setOnMapTouchListener(motionEvent -> {
            if (mTouchHelper == null) {
                mTouchHelper = TouchHelper.newInstance().addTouchListener(new TouchHelper.TouchListenerProxy() {
                    @Override
                    public void handlerUpTouch(float downX, float downY, float upX, float upY) {
                        //纵向滑动距离小于-100px
                        if (mIsExpand && upY - downY < -100) {
                            binding.mlFilterRoot.transitionToEnd();
                        }
                    }
                });
            }
            mTouchHelper.onTouch(null, motionEvent);
        });
    }

    private String getSearchText() {
        return binding.etView.getText().toString();
    }

    private void resetSearchContent() {
        binding.etView.setText("");
    }

    private void resetFilterData() {
//        resetSendLocationData();
        resetPurposeLocationData();
        resetCarType();
        resetCarLen();
        resetGoodsType();
    }

    private void resetCarLen() {
        if (carsLengthPopWindow != null) {
            carsLengthPopWindow.resetSelectItem();
        }
        viewModel.carLength.set(new GoodsInfoTypeEntity3());
        TextViewUtils.changeTextView(getContext(), binding.carLen, R.mipmap.ic_down_arrow_n, false);
        binding.carLen.setText("车长");
        binding.llCarlen.setBackgroundResource(R.drawable.shape_gray_coner);
        lengthPosition = 0;
        carsLengthPopWindow.setData(VehicleConstant.sortCarLength(carsLengthData), lengthPosition);
    }

    private void resetGoodsType() {
        if (goodsTypePopWindow3 != null) {
            goodsTypePopWindow3.resetSelectItem();
        }
        viewModel.findGoodsType.set(new GoodsInfoTypeEntity3());
        TextViewUtils.changeTextView(getContext(), binding.goodsType, R.mipmap.ic_down_arrow_n, false);
        binding.goodsType.setText("找货类型");
        binding.llGoodsType.setBackgroundResource(R.drawable.shape_gray_coner);
        goodTypePosition = 0;
        goodsTypePopWindow3.setData(VehicleConstant.goodsType(), goodTypePosition);
    }

    private void resetCarType() {
        if (carsTypePopWindow != null) {
            carsTypePopWindow.resetSelectItem();
        }
        viewModel.carType.set(new GoodsInfoTypeEntity3());
        binding.tabLayoutType.selectTab(binding.tabLayoutType.getTabAt(0));
    }

    private void resetPurposeLocationData() {
        if (destinationPopWindow != null) {
            destinationPopWindow.resetDataAndUI();
        }
        viewModel.purposeLocation.set(new GoodsSourceLocationEntity());
        TextViewUtils.changeTextView(getContext(), binding.tvDestination, R.mipmap.ic_down_arrow_n, false);
        binding.tvDestination.setText("目的地");
        binding.llDestination.setBackgroundResource(R.drawable.shape_gray_coner);
    }

    private void resetSendLocationData() {
        if (areaWindow != null) {
//            binding.tvSend.setText(DefaultUtil.getMaxLengthText("全国", 2));
            String cityName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.City, "乌鲁木齐");
            binding.tvSend.setText(cityName.replaceAll("市", ""));
        }
        viewModel.sendLocation.set(new GoodsSourceLocationEntity());
//        resetMap();
    }

    private void resetMap() {
        mZoom = mMinZoom;
        mIsNeedLoadByCamera = false;
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mCenterLatLng, mZoom));
    }

    /**
     * 刷新数据
     * （列表下拉刷新或者改变筛选条件）
     */
    private void refreshData() {
        refreshDataByPage(1);
    }

    /**
     * 请求数据（不刷新）
     */
    private void requestData() {
        if (mapShowing) {
            viewModel.getMapCar(getSearchText());
        } else {
            viewModel.getListCar(page, getSearchText());
        }
    }

    private void refreshDataByPage(int page) {
        this.page = page;
        if (mapShowing) {
            if (page <= 1) {
                clearMarker();
            }
            viewModel.getMapCar(getSearchText());
        } else {
            if (page <= 1)
                isLoadMore = false;
            viewModel.getListCar(page, getSearchText());
        }
    }

    //列表
    public void getCarrierInfoData(List<CarriageInfo> list) {
        binding.carsListRefreshLayout.finishRefresh();
        if (isLoadMore) {
            binding.carsListRefreshLayout.finishLoadMore();
            if (list.size() > 0) {
                carrierDemandListAdapter.addData(list);
            } else {
                binding.carsListRefreshLayout.finishLoadMoreWithNoMoreData();
            }
            binding.carsList.setVisibility(View.VISIBLE);

        } else {
            binding.imgBackTop.setVisibility(View.GONE);
            binding.carsListRefreshLayout.finishRefresh();
            if (list.size() > 0) {
                if (!mapShowing) {
                    binding.carsList.setVisibility(View.VISIBLE);
                    binding.carsListRefreshLayout.setVisibility(View.VISIBLE);
                    binding.emptyView.setVisibility(View.GONE);
                }
                carrierDemandListAdapter.setDatas(list);
                if (list.size() < 10) {
                    binding.carsListRefreshLayout.finishLoadMoreWithNoMoreData();
                }
            } else {
                carrierDemandListAdapter.setDatas(null);
                if (!mapShowing) {
                    binding.carsList.setVisibility(View.GONE);
                    binding.emptyView.setVisibility(View.VISIBLE);
                }
            }
        }
    }

    private void showSendPopWindow() {
        showPopup(areaWindow);
    }

    private void showDestinationPopWindow() {
        showPopup(destinationPopWindow);
    }


    private void loadData() {
        String provinceName = "", cityName = "", areaName = "不限";
        if (LocationUtil.isOpenLocation(getContext())) {
            provinceName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.Province, "新疆");
            cityName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.City, "乌鲁木齐");
        } else {
            provinceName = "新疆";
            cityName = "乌鲁木齐";
        }
        if (cityName.endsWith("市")) {
            //针对直辖市处理(适应接口)
            cityName = cityName.substring(0, cityName.length() - 1);
        }
        binding.tvSend.setText(cityName);
        binding.llSend.setBackgroundResource(R.drawable.shape_theme_coner);
        TextViewUtils.changeTextView(getActivity(), binding.tvSend, R.mipmap.ic_down_arrow, true);
        //
        viewModel.getCarTypeList();
        viewModel.getAddressModel();
    }

    private void initLocationData() {
        if (PermissionUtils.checkPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION)) {
            //设置经纬度
            double lat = NumberUtil.convertToDouble(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LATITUDE_ID, "0"));
            double log = NumberUtil.convertToDouble(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LONGITUDE_ID, "0"));
            //设置定位信息
            mCurLatLng = new LatLng(lat, log);
            viewModel.ldLaction.getValue().setLatitude(lat);
            viewModel.ldLaction.getValue().setLongitude(log);
        }
        if ("全国".equals(binding.tvSend.getText().toString())) {
            //地图缩小展示全中国
            mZoom = mMinZoom;
            mIsNeedLoadByCamera = true;
            aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mCenterLatLng, mZoom));
            refreshData();
        } else {
            //查找经纬度刷新地图
            if (LocationUtil.isOpenLocation(getContext())) {
                String provinceName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.Province, "新疆");
                String cityName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.City, "乌鲁木齐");
                String areaName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.Area, "天山");
                //查找设置省市no
                findAddressCode(provinceName, cityName);
                //获取定位数据
                viewModel.getLocation(getActivity(), cityName, areaName);
            } else {
                //查找设置省市no
                findAddressCode("新疆", "乌鲁木齐");
                //获取定位数据
                viewModel.getLocation(getActivity(), "乌鲁木齐", "天山");
            }
        }
    }

    private void findAddressCode(String provinceName, String cityName) {
        AddressEntity[] code = AddressHelper.getInstance().findCode(provinceName, cityName, "");
        if (code != null && code.length >= 3) {
            //设置省市区简称no
            if (code[0] != null) {
                viewModel.sendLocation.get().setProvinceNo(code[0].getNo());
                viewModel.sendLocation.get().setProvinceName(code[0].getSimpleName());
            }
            if (code[1] != null) {
                viewModel.sendLocation.get().setCityNo(code[1].getNo());
                viewModel.sendLocation.get().setCityName(code[1].getSimpleName());
            }
        }
    }

    private void showCarsTypePopWindow() {
        carsTypePopWindow.showPopwindow(binding.tabLayoutType, 0, 0);
        carsTypePopWindow.setData(carsTypeData, typePosition);
    }

    private void showCarsLengthPopWindow() {
        carsLengthPopWindow.setData(VehicleConstant.sortCarLength(carsLengthData), lengthPosition);
        showPopup(carsLengthPopWindow);
    }

    private void showGoodsTypeWindow() {
        goodsTypePopWindow3.setData(VehicleConstant.goodsType(), goodTypePosition);
        showPopup(goodsTypePopWindow3);
    }

    /**
     * 展示选择弹窗
     */
    public void showPopup(BasePopWindow pop) {
        if (getActivity() instanceof MainActivity) {
            EventBus.getDefault().post(LogisticsEvent.make().setMessageTag(EventConstant.EVENT_LOGISTICS_WINDOW_TOP));
            new Handler().postDelayed(() -> pop.showPopwindow(binding.line4, 0, 0), 300);
        } else {
            pop.showPopwindow(binding.line4, 0, 0);
        }
    }

    @Override
    public void onClick(View v) {
        if (ClickUtils.isDoubleClick()) {
            return;
        }
        switch (v.getId()) {
            case R.id.type_more:
                if (null != carsTypeData && carsTypeData.size() > 0) {
                    binding.typeMore.setImageResource(R.mipmap.icon_tab_pack_up);
                    showCarsTypePopWindow();
                }
                break;
            case R.id.length_more:
                if (null != carsLengthData && carsLengthData.size() > 0) {
                    showCarsLengthPopWindow();
                }
                break;
            case R.id.ll_send:
                LOCATION_TYPE = 0;
                if (null != addressEntityList && addressEntityList.size() > 0) {
                    showSendPopWindow();
                } else {
                    viewModel.getAddressModel();
                }
                setOptionStatus(1);
                break;
            case R.id.ll_destination:
                LOCATION_TYPE = 1;
                if (null != addressEntityList && addressEntityList.size() > 0) {
                    showDestinationPopWindow();
                } else {
                    viewModel.getAddressModel();
                }
                setOptionStatus(2);
                break;
            case R.id.ll_carlen:
                if (null != carsLengthData && carsLengthData.size() > 0) {
                    showCarsLengthPopWindow();
                }
                setOptionStatus(3);
                break;

            case R.id.ll_goods_type:
                showGoodsTypeWindow();
                setOptionStatus(4);
                break;

            case R.id.img_back_top:
                binding.carsList.smoothScrollToPosition(0);
                break;
            case R.id.tv_search_car:
                boolean canSearch = !TextUtils.isEmpty(getSearchText());
                if (!canSearch) {
                    MToast.showToast(getContext(), "请先输入搜索内容");
                    return;
                }
                isCameraToPosition = true;
                refreshData();
                break;
            case R.id.iv_map_list:
                if (mapShowing) {
                    mapShowing = false;
                    Resources res = getActivity().getResources();
                    Drawable imgs = res.getDrawable(R.drawable.ditu_blue_black);
                    imgs.setBounds(0, 0, imgs.getMinimumWidth(), imgs.getMinimumHeight());
                    binding.ivMapList.setCompoundDrawables(imgs, null, null, null);
                    binding.ivMapList.setText("图查");
                    binding.flMap.setVisibility(View.GONE);
                    binding.listDataLayout.setVisibility(View.VISIBLE);
                } else {
                    mapShowing = true;
                    Resources res = getActivity().getResources();
                    Drawable imgs = res.getDrawable(R.drawable.liebiao_black);
                    imgs.setBounds(0, 0, imgs.getMinimumWidth(), imgs.getMinimumHeight());
                    binding.ivMapList.setCompoundDrawables(imgs, null, null, null);
                    binding.ivMapList.setText("列表");
                    binding.listDataLayout.setVisibility(View.GONE);
                    binding.flMap.setVisibility(View.VISIBLE);
                }
                refreshData();
                break;
            case R.id.tv_find_car_by_map_load:
                //加载车辆，手动点击时清空省市区no
                viewModel.sendLocation.get().setProvinceNo("");
                viewModel.sendLocation.get().setCityNo("");
                viewModel.sendLocation.get().setAreaNo("");
                viewModel.getMapCar("");
                //暂时去掉地图移动修改发货地展示
//                cityByLocation(mCurLatLng.latitude, mCenterLatLng.longitude);
                break;
        }
    }

    private void setOptionStatus(int index) {
        switch (index) {
            case 1:
                binding.llSend.setBackgroundResource(R.drawable.shape_gray_coner);
                TextViewUtils.changeTextView(getActivity(), binding.tvSend, R.mipmap.ic_up_arrow_n, false);
                break;
            case 2:
                binding.llDestination.setBackgroundResource(R.drawable.shape_gray_coner);
                TextViewUtils.changeTextView(getActivity(), binding.tvDestination, R.mipmap.ic_up_arrow_n, false);
                break;
            case 3:
                binding.llCarlen.setBackgroundResource(R.drawable.shape_gray_coner);
                TextViewUtils.changeTextView(getActivity(), binding.carLen, R.mipmap.ic_up_arrow_n, false);
                break;
            case 4:
                binding.llGoodsType.setBackgroundResource(R.drawable.shape_gray_coner);
                TextViewUtils.changeTextView(getActivity(), binding.goodsType, R.mipmap.ic_up_arrow_n, false);
                break;
        }
    }

    /**
     * 通过经纬度获取位置信息
     *
     * @param lat
     * @param lon
     */
    public void cityByLocation(double lat, double lon) {
        GeocodeSearch geocodeSearch = new GeocodeSearch(getActivity());
        // 第一个参数表示一个LatLng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
        RegeocodeQuery query = new RegeocodeQuery(new LatLonPoint(lat,
                lon), 200, GeocodeSearch.AMAP);
        geocodeSearch.getFromLocationAsyn(query);
        //搜索位置信息
        geocodeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult result, int code) {
                if (code != 1000) return;
                RegeocodeAddress address = result.getRegeocodeAddress();
                if (address != null) {
                    refreshSendCitySelect(address.getProvince(), address.getCity(), address.getDistrict());
                }
            }

            @Override
            public void onGeocodeSearched(GeocodeResult result, int code) {

            }
        });
    }

    //地图移动时刷新发货地文字
    private void refreshSendCitySelect(String province, String city, String district) {
        destinationPopWindow.setDataAndPosition(addressEntityList, province, city, district);
        BaseAreaEntity[] entities = destinationPopWindow.findCode(province, city, district);
        binding.tvSend.setText(entities[1].getSimpleName());
    }

    public void initAddressData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> datas) {
        addressEntityList = datas;
        //查找地址下标
        String provinceName = "", cityName = "", areaName = "不限";
        if (LocationUtil.isOpenLocation(getContext())) {
            provinceName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.Province, "新疆");
            cityName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.City, "乌鲁木齐");
        } else {
            provinceName = "新疆";
            cityName = "乌鲁木齐";
        }
        areaWindow.setDataAndPosition(addressEntityList, provinceName, cityName, areaName);
        destinationPopWindow.setDataAndPosition(addressEntityList, provinceName, cityName, areaName);
//        destinationPopWindow.setData(addressEntityList, true);
//        if (LOCATION_TYPE == 1) {
//            showDestinationPopWindow();
//        } else if (LOCATION_TYPE == 0) {
//            showSendPopWindow();
//        }
    }

    //获取车型
    public void getCarsTypeData(List<GoodsInfoTypeEntity3> list) {
        if (null != list && list.size() > 0) {
            carsTypeData = list;
            //todo 判断是否有默认选中类型
            int index = 0;
            for (int i = 0; i < list.size(); i++) {
                GoodsInfoTypeEntity3 entity3 = list.get(i);
                binding.tabLayoutType.addTab(binding.tabLayoutType.newTab().setText(entity3.getName()));
                if (!TextUtils.isEmpty(mInitCarTypeNo) && mInitCarTypeNo.equals(entity3.getNo())) {
                    index = i;
                }
            }
            int finalIndex = index;
            binding.tabLayoutType.postDelayed(() -> {
                binding.tabLayoutType.selectTab(binding.tabLayoutType.getTabAt(finalIndex));
                typePosition = finalIndex;
                viewModel.carType.set(carsTypeData.get(finalIndex));
                //初始化监听
                initTabListener();
                //开始定位并刷新数据
                initLocationData();
            }, 100);
        } else {
            MToast.showToast(getActivity(), "数据未加载");
        }
    }

    //获取车长
    public void getCarsLengthData(List<GoodsInfoTypeEntity3> list) {
        if (null != list && list.size() > 0) {
            carsLengthData = list;
          /*  for(int i=0;i<list.size();i++){
                binding.tabLayoutLength.addTab(binding.tabLayoutLength.newTab().setText(list.get(i).getName()));
            }*/
        }
    }


    /**
     * 根据车型筛选数据
     */
    private void filterByCarType() {
        //切换车型时重置车长，填充车长筛选数据
        lengthPosition = 0;
        viewModel.carLength.set(null);
        //刷新车长数据
        if (carsTypeData != null && carsTypeData.size() > 0) {
            carsLengthData = carsTypeData.get(typePosition).getCarLenList();
        }
        //刷新
        refreshData();
    }

    /**
     * 清除页面marker
     */
    private void clearMarker() {
        if (aMap != null)
            aMap.clear();
        if (mMarkers != null)
            mMarkers.clear();
        if (carEntities != null)
            carEntities.clear();
    }

    /**
     * 刷新地图覆盖物
     */
    private void refreshMapMarker(List<MapCarEntity> list) {
        if (list == null || list.size() == 0) {
            MToast.showToast(getActivity(), "没有更多数据了");
            if (isCameraToPosition) {
                isCameraToPosition = false;
                double lat = NumberUtil.convertToDouble(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LATITUDE_ID, "0"));
                double log = NumberUtil.convertToDouble(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LONGITUDE_ID, "0"));
                cameraToPosition(lat, log);
            }
            return;
        }
        //添加新marker，旧数据去重
        for (MapCarEntity entity : list) {
            if (entity.getLatitude() <= 0 || entity.getLongitude() <= 0) {
                return;
            }
            if (!TextUtils.isEmpty(entity.getCarrierNo())) {
                if (carEntities == null)
                    carEntities = new HashMap<>();
                if (carEntities.size() > 0) {
                    if (!carEntities.keySet().contains(entity.getCarrierNo())) {
                        carEntities.put(entity.getCarrierNo(), entity);
                        addMarker(entity);
                    }
                } else {
                    carEntities.put(entity.getCarrierNo(), entity);
                    addMarker(entity);
                }
            }
        }
    }

    /**
     * 添加覆盖物
     */
    private void addMarker(MapCarEntity entity) {
        //去重
        for (Marker marker : mMarkers) {
            MapCarEntity oldEntity = (MapCarEntity) marker.getObject();
            //更新marker数据，并返回
            if (oldEntity != null && oldEntity.getCarrierNo().equals(entity.getCarrierNo())) {

                marker.setObject(entity);
                marker.setPosition(new LatLng(entity.getLatitude(), entity.getLongitude()));
                //根据消息状态设置marker图标
                marker.setIcon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_find_car_marker_yellow));
                return;
            }
        }
        MarkerOptions markerOption = new MarkerOptions();
        markerOption.position(new LatLng(entity.getLatitude(), entity.getLongitude()));
        markerOption.icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_find_car_marker_yellow));
        Marker marker = aMap.addMarker(markerOption);
        //设置附着对象
        marker.setObject(entity);
        mMarkers.add(marker);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MenuEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_ORDER_FINISH) {
            refreshData();
        }
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {

    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        //设置定位信息
        mCurLatLng = cameraPosition.target;
        viewModel.ldLaction.getValue().setLatitude(mCurLatLng.latitude);
        viewModel.ldLaction.getValue().setLongitude(mCurLatLng.longitude);
        cityByLocation(mCurLatLng.latitude, mCurLatLng.longitude);
        //设置当前半径
        setCurrentRadius();
        //比较缩放比例
        if (viewModel.ldLaction.getValue().getZoom()!=cameraPosition.zoom) {
            //设置当前缩放比例
            viewModel.ldLaction.getValue().setZoom(cameraPosition.zoom);
            return;
        }
        requestData();
    }

    /**
     * 设置当前半径
     */
    private void setCurrentRadius() {
        //计算并设置设置当前半径(单位：米)
        if (mScreenWidth == 0) {
            mScreenWidth = ScreenUtil.getDisplayWidth();
        }
        //屏幕高度的一半 * 当前缩放1px代表的米数
        String radius = NumberUtil.trim0(mScreenWidth / 2f * aMap.getScalePerPixel());
        //设置半径
        viewModel.radius = radius;
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        MapCarEntity entity = (MapCarEntity) marker.getObject();
        marker.hideInfoWindow();
        marker.setIcon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_find_car_marker_yellow_click));
        mLastMarker = marker;
        //显示弹窗
        mMapCarPop.setData(entity);
        mMapCarPop.showPopwindowBottom(binding.mapFindCarByMap);
        return false;
    }


    @Override
    public void onResume() {
        super.onResume();
        binding.mapFindCarByMap.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        binding.mapFindCarByMap.onPause();
    }

    @Override
    public void onSaveInstanceState(@NotNull Bundle outState) {
        super.onSaveInstanceState(outState);
        binding.mapFindCarByMap.onSaveInstanceState(outState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        binding.mapFindCarByMap.onDestroy();
    }
}
